﻿#!/usr/bin/env python
#

import time
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.api import urlfetch
from google.appengine.api import mail
import httplib, urllib,re
import datetime
import ConfigParser
import sys 
from prettytable import PrettyTable

import logging 


class FundValue(webapp.RequestHandler):  
    logging.logMultiprocessing = 0 
    
    sys.setdefaultencoding('gb2312') 
    FUND_CODE = "161706"
    SALE_DATE="2007-06-22"
    SALE_MONEY = 5000.0
    TODAY_DATE=datetime.date.today()
    
    PANEL = "biz.finance.sina.com.cn"
    USERAGENT = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.1) Gecko/20060111 Firefox/1.5.0.1'
    PATH="/fundinfo/open/lsjz.php?fund_code="

    x = PrettyTable(["Code", "Name", "Buy Value", "Buy Count", "Today Vlue", "Profits"])
    #x = PrettyTable(["code", "1", "2", "3", "4", "5"])
    x.align= "l" 

    def get_found_value(self,fund_code,sale_date,sale_money):
        params = urllib.urlencode({"startdate1":sale_date,"enddate1":self.TODAY_DATE})
        headers = {"Content-type": "application/x-www-form-urlencoded",
                   "Accept": "text/plain",
                   "Referer" :'https://'+self.PANEL+self.PATH+fund_code,"User-Agent":self.USERAGENT}
        conn = httplib.HTTPConnection(self.PANEL)
        conn.request("POST", self.PATH+fund_code, params, headers)
        response = conn.getresponse()
        data = response.read()
        html=data.decode("gb2312")
        conn.close();
        pattern = '<title>(.+)\('+fund_code+'\)'
        all_matches = re.findall(pattern,html);
        
        fund_name =  all_matches[0]#.encode("utf8")
        
        pattern='<a href=\'./lsjz_dwjz.php\?jzrq=(.*)\'[\s]+target=_blank>(.*)</a>'
        all_matches=re.findall(pattern,html);
        
        today_value =  float(all_matches[0][1])
        sale_value = float(all_matches[len(all_matches)-1][1])
        sale_count = sale_money/sale_value
        value=(today_value-sale_value)*sale_count
        #return "|"+self.construct_block(10,fund_code)+"|"+self.construct_head_block(20,fund_name)+"|"+self.construct_block(10,sale_value.__str__())+"|"+self.construct_block(20,sale_count.__str__())+"|"+self.construct_block(10,today_value.__str__())+"|"+self.construct_block(20,value.__str__())+"|\n"
        #return "\t "+fund_code+" \t "+fund_name+" \t "+sale_value.__str__()+" \t\t\t\t "+sale_count.__str__()+" \t "+today_value.__str__()+" \t\t\t "+value.__str__()+" \t\n "
        self.x.add_row([fund_code,fund_name, sale_value.__str__(), sale_count.__str__(),today_value.__str__(),value.__str__()])
        
    def SendNoticeMail(self,body):
        message = mail.EmailMessage(sender='guoyao@gmail.com',
                                    subject='Fund Value')
        message.to = 'guoyao@gmail.com'
        message.body = body
        message.send()

    def get(self):
     
    
        self.get_found_value("110002","2007-10-22",1000.0)
        self.get_found_value("110002","2007-09-14",3000.0)
        
        self.get_found_value("162703","2007-09-14",2000.0)
        self.get_found_value("162703","2007-10-22",2000.0)
        
        self.get_found_value("070003","2007-09-17",3000.0)
        
        #print(self.x.get_string())
      
      #sms=sms+self.get_found_value("002011","2007-09-26",2000.0)
      
        self.SendNoticeMail(self.x)
        #print self.x

application = webapp.WSGIApplication([
  ('/FundValue', FundValue),
  ('/tasks/FundValue', FundValue)
], debug=True)


def main():
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()


